<template>
  <pageTabelLayout>
    <template #pageHeader>
      <!-- 排产工序LT设置 -->
      <div class="my-header">
        <!-- <div class="search-form" v-if="headerShow">
              <a-form size="small" :model="pageData" layout="inline">
                  <a-form-item label="布类">
                      <a-select popup-container="html"  :loading="loading" :allowClear="true"
                          @search="handleSearch" v-model="pageData.dropDownData" :filter-option="false" allow-search
                          @focus="focusSel">
                          <a-option v-for="item in pageData.clothList" :value="item">{{ item }}</a-option>
                      </a-select>
                  </a-form-item>
              </a-form>
          </div> -->
        <!-- <div class="my-divisders">
              <a-divider orientation="center">
                  <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
                  <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
              </a-divider>
          </div> -->
        <div class="my-tool-bar">
          <!-- <Toolbar :items="['新增', '删除',]" @add="addHandler" @import="importHandler" @del="deleteHandler"
            @select="selectHandler" @export="exports" @excel="downloadHandler">
          </Toolbar> -->
          <div class="bg-container-1">
            <div>
              <el-button type="primary" :icon="Search" class="stbutencx" @click="selectHandler">查询</el-button>
              <el-button type="success" :icon="CirclePlus" class="stbutenxz" @click="addHandler">新增</el-button>
              <el-button plain :icon="Delete" @click="deleteHandler">删除</el-button>
            </div>
          </div>
        </div>
      </div>
    </template>
    <!-- <a-tabs   :justify="true">
      <a-tab-pane title="排产工序LT设置">
        <a-table style="height: 100%;" size="mini" :scrollbar="scrollbar" sticky-header stripe :bordered="true"
          :columns="columns" :row-selection="{ showCheckedAll: true, width: 50, onlyCurrent: true, }"
          v-model:selected-keys="selectedRowKeys" :loading="table.tableLoading" :data="tableCon.tableConter"
          :pagination="false" :rowKey="rowKey" >
          <template #action="{ record }">
            <a-button type="primary" size="mini" status="warning" @click="editHandler(record)">
              <template #icon>
                <icon-edit />
              </template>
              修 改
            </a-button>
          </template>
        </a-table>
      </a-tab-pane>
    </a-tabs> -->
    <template #pageTabel>
      <AgGridVuesCopys style="height:calc(100% - 90px)" class="ag-theme-alpine" :columnDefs="tc"
                       :rowData="tableCon.tableConter"
                       :defaultColDef="defaultColDef" rowSelection="multiple" @grid-ready="gridReady">
      </AgGridVuesCopys>
      <paginationCopys :total="paging.total" v-model:current="pages" show-page-size show-total show-jumper size="mini"
                       @change="pagingChange" @page-size-change="pagingSizeChange" :page-size="paging.size"/>
    </template>
    <a-drawer :drawer-style="{ zIndex: 9999 }" :mask-closable="false" :width="400" :visible="pageData.showAdd"
              unmountOnClose @ok="sideOk" @cancel="pageData.showAdd = false" cancel-text="关闭" ok-text="保存">
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" :model="dataForm">
          <!-- <a-form-item label="序号" field="serialNumber" :rules="[{ required: true, message: '序号必填' }]"
            :validate-trigger="['change', 'blur']" label-col-flex="40px">
            <a-input-number v-model="dataForm.serialNumber" class="input-demo" :min="0"
              :max="1000000000000000000000000000000000" />
          </a-form-item> -->
          <a-form-item label="工序" field="process" :validate-trigger="['change', 'blur']"
                       :rules="[{ required: true, message: '工序必填' }]" label-col-flex="70px">
            <!-- <a-input v-model="dataForm.process" /> -->
            <a-select popup-container="html" :loading="loading" :allowClear="true" @search="handleSearch"
                      v-model="dataForm.process"
                      :filter-option="false" allow-search @focus="focusSel" class="bacClass">
              <a-option v-for="item in pageData.clothList" :value="item.processName">{{
                  item.processName
                }}
              </a-option>
            </a-select>
          </a-form-item>
          <a-form-item label="时间" field="completionTime" :validate-trigger="['change', 'blur']"
                       :rules="[{ required: true, message: '时间必填' }, { match: /^[1-9]\d*\.?\d?$|^0\.\d$/, message: '时间格式不正确' }]"
                       label-col-flex="70px">
            <a-input v-model="dataForm.completionTime" @blur="sqblur"/>
          </a-form-item>
          <a-form-item label="备注" field="remark" label-col-flex="70px">
            <a-textarea v-model="dataForm.remark" default-value=""
                        style="background-color: #fff; border: 1px solid #cccccc"/>
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
  </pageTabelLayout>
</template>

<script lang="ts">
import {post, get} from '@/api/http'
import {Search, CirclePlus, Delete} from '@element-plus/icons-vue'
import {
  useTable,
  useRowKey,
  useTableColumn,
  usePagination,
  useRowSelection,
} from '@/hooks/table'

import {ref, reactive, onMounted, onActivated, onUnmounted} from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import {Form, Message, Modal, Pagination} from '@arco-design/web-vue'
import {FormInstance} from '@arco-design/web-vue/es/form'
import emitter from '@/hooks/useEventBus'
import validate from '@/hooks/useValidate'
//import { baseURL } from '../../../api/axios.config'
import axios from 'axios'
import filedownload from 'js-file-download'
import 'ag-grid-community/styles/ag-grid.css'
import 'ag-grid-community/styles/ag-theme-alpine.css'


interface ClothSet {
  id?: any
  serialNumber?: number | undefined
  mercery?: string | undefined
  deleteState?: any
  remark?: string | undefined
  createName?: string | undefined
  createTime?: string | undefined
  updateName?: string | undefined
  updateTime?: string | undefined
  process?: string | undefined
  completionTime?: string | undefined
}

interface pagings {
  size: number | string
  total: number | string
}

export default {
  name: 'productionModeLt',
  setup() {
    //  const headerShow = ref<boolean>(true)
    //查询
    const scrollbar = ref(true)
    const pages = ref(1)
    const paging: pagings = reactive({
      size: 10,
      total: 30,
    })

    function doRefresh() {
      pageData.pageLoading = true

      post({
        url: '/aps/schedulProcess/getPage',
        data: {
          page: pages.value,
          limit: paging.size,
          deleteState: 0,
        },
      })
          .then(({data, code}: any) => {
            if (code === 200) {
              //  console.log(data, "结果");
              tableCon.tableConter = data.data
              paging.total = data.total
            }
          })
          .catch(console.log)
          .finally(() => {
            pageData.pageLoading = false
          })
    }

    const {selectedRowKeys, onSelectionChange} = useRowSelection()
    const pagination = usePagination(doRefresh)
    const table = useTable()
    const rowKey = useRowKey('id')
    //检验表单是否含有中文的方法
    const hasChiese = validate.includeChinese
    const columns = [
      // {
      //   title: '顺号',
      //   key: "id",
      //   width: 150,
      //   align: "center",
      //   dataIndex: 'id',
      // },
      {
        title: '工序',
        key: 'process',
        width: 150,
        dataIndex: 'process',
        align: 'center',
      },
      {
        title: '时间',
        key: 'completionTime',
        width: 150,
        dataIndex: 'completionTime',
        align: 'center',
      },
      {
        title: '备注',
        key: 'remark',
        width: 150,
        dataIndex: 'remark',
        align: 'center',
      },
      {
        title: '建立人',
        key: 'createName',
        width: 150,
        dataIndex: 'createName',
        align: 'center',
      },
      {
        title: '建立时间',
        key: 'createTime',
        width: 100,
        dataIndex: 'createTime',
        align: 'center',
        ellipsis: true,
        tooltip: true,
      },
      {
        title: '修改人',
        key: 'updateName',
        width: 150,
        dataIndex: 'updateName',
        align: 'center',
      },
      {
        title: '修改时间',
        key: 'updateTime',
        width: 150,
        dataIndex: 'updateTime',
        align: 'center',
      },
      {
        title: '操作',
        key: 'id',
        width: 150,
        dataIndex: 'id',
        slotName: 'action',
        fixed: 'right',
        align: 'center',
      },
    ]
    /************************************** */
    const columnDefs = [
      {
        headerName: '', //选择列头部显示的文字，可以为空
        checkboxSelection: true, //设置为ture显示为复选框
        headerCheckboxSelection: true, //表头是否也显示复选框，全选反选用
        pinned: 'left', //固定再左边
        width: 50, //列的宽度
      },
      {headerName: '工序', field: 'process'},
      {headerName: '时间', field: 'completionTime'},
      {headerName: '备注', field: 'remark'},
      {headerName: '建立人', field: 'createName'},
      {headerName: '建立时间', field: 'createTime'},
      {headerName: '修改人', field: 'updateName'},
      {headerName: '修改时间', field: 'updateTime'},
      {headerName: '操作'},
    ]
    const rowData = [
      {make: 'Toyota', model: 'Celica', price: 35000},
      {make: 'Ford', model: 'Mondeo', price: 32000},
      {make: 'Porsche', model: 'Boxster', price: 72000},
      {make: 'Toyota', model: 'Celica', price: 35000},
      {make: 'Ford', model: 'Mondeo', price: 32000},
      {make: 'Porsche', model: 'Boxster', price: 72000},
      {make: 'Toyota', model: 'Celica', price: 35000},
      {make: 'Ford', model: 'Mondeo', price: 32000},
      {make: 'Porsche', model: 'Boxster', price: 72000},
    ]
    const defaultColDef = {
      sortable: true,
      filter: true,
      // flex: 1,
      resizable: true,
    }
    let tc: any[] = columnDefs.map((o) => {
      //let obj = {}
      if (o.headerName === '操作') {
        o['resizable'] = false
        o['filter'] = false
        o['sortable'] = false
        o['pinned'] = 'right'
        o['width'] = 80
        o['cellRenderer'] = {
          template: `
            <el-button style="color:#165dff;" link @click="a">修改</el-button>`,
          setup(props: any) {
            const a = () => {
              editHandler(props.params.data)
            }
            return {
              a,
            }
          },
        }
      }
      return o
    })
    const gridOption = ref()
    const gridReady = (params: any) => {
      console.log(params, 123321)
      gridOption.value = params.api
    }
    /***************************************** */
    const tableCon = reactive({
      tableConter: [],
    })
    //页改变
    const pagingChange = (current: number) => {
      // console.log(current, "分页改变");
      pages.value = current
      doRefresh()
    }
    //页条改变
    const pagingSizeChange = (pageSize: number) => {
      //  console.log(pageSize, "条数")
      pages.value = 1
      paging.size = pageSize
      doRefresh()
    }
    const alone = (rowKeys, rowKey, record) => {
      // console.log(rowKeys);
      // console.log(rowKey);
      // console.log(record);
    }
    const alonell = (selected, selectedRows) => {
      // console.log(selected);
      // console.log(selectedRows);
    }
    const scroll = {
      x: 2000,
      y: 200,
    }
    const tablediv = ref(null)
    const pageData = reactive<{
      clothList: ClothSet[]
      showAdd: boolean
      sideTitle: string
      dropDownData: any
      pageLoading: boolean
      theight: number
      tablediv: any
      rHeight: number | undefined
    }>({
      clothList: [],
      showAdd: false,
      sideTitle: '新增资料',
      dropDownData: '',
      pageLoading: false,
      theight: 0,
      tablediv: null,
      rHeight: 0,
    })
    //下拉框得到焦点
    const focusSel = () => {
      selCxAll({processName: ''})
    }
    //下拉数据
    const options = ref<any>(pageData.clothList)
    const loading = ref(false)
    const handleSearch = (value: any) => {
      if (value) {
        const ob = {processName: value}
        loading.value = true
        selCxAll(ob)
        options.value = pageData.clothList
        loading.value = false
      } else {
        options.value = []
      }
    }

    //下拉框查询
    function selCxAll(val: any) {
      post({
        url: '/pdm/workprocedure/select',
        data: val,
      }).then(({data, code}: any) => {
        if (code === 200) {
          // console.log(data,"下拉工序名称");
          pageData.clothList = data
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }

    onMounted(() => {
      doRefresh()
    })
    //查询
    const selectHandler = () => {
      pages.value = 1
      doRefresh()
    }
    const queryData = reactive({
      clothType: '',
    })
    const addHandler = () => {
      for (var key in dataForm) {
        if (key === 'id') {
          dataForm[key] = null
        } else if (key == 'serialNumber') {
          dataForm[key] = 0
        } else {
          dataForm[key] = ''
        }
      }
      pageData.showAdd = true
      pageData.sideTitle = '新增资料'
    }
    const dataForm = reactive<ClothSet>({
      id: null,
      process: '',
      completionTime: '',
      remark: '',
    })
    const formRef = ref<FormInstance>()
    const sideOk = () => {
      formRef.value?.validate().then((err) => {
        if (!err) {
          if (pageData.sideTitle === '新增资料') {
            post({
              url: '/aps/schedulProcess/insert',
              data: [dataForm],
            }).then((res: any) => {
              if (res.code === 200) {
                formRef.value?.resetFields()

                pageData.showAdd = false

                Message.success({
                  content: '新增成功',
                  duration: 5000,
                })
                doRefresh()
              } else {
                Message.error({
                  content: res.message,
                  duration: 5000,
                })
              }
            })
          } else {
            post({
              url: '/aps/schedulProcess/update',
              data: [dataForm],
            }).then((res: any) => {
              if (res.code === 200) {
                formRef.value?.resetFields()
                pageData.showAdd = false

                Message.success({
                  content: '修改成功',
                  duration: 5000,
                })
                doRefresh()
              } else {
                Message.error({
                  content: res.message,
                  duration: 5000,
                })
              }
            })
          }
        }
      })
    }
    const deleteHandler = () => {
      var arr = []
      arr = gridOption.value.getSelectedRows().map((item) => {
        return item.id
      })
      if (arr.length === 0) {
        Message.warning({
          content: '请选择要删除的数据',
          duration: 5000,
        })
        return
      }
      Modal.confirm({
        title: '系统提示',
        content: '确认删除选中的数据?',
        onOk() {
          post({
            url: '/aps/schedulProcess/delete',
            data: arr,
          }).then(({code, data}: any) => {
            if (code === 200) {
              Message.success({
                content: '删除成功',
                duration: 5000,
              })
              // if (selectedRowKeys.value.length == tableCon.tableConter.length) {
              //   pages.value > 1 ? pages.value-- : pages.value = 1
              //   doRefresh();
              // } else {
              //   doRefresh();
              // }
              pages.value = 1
              doRefresh()
            } else {
              Message.error({
                content: '删除失败',
                duration: 5000,
              })
            }
            selectedRowKeys.value = []
          })
        },
      })
    }
    const editHandler = (record: ClothSet) => {
      for (var key in record) {
        dataForm[key] = record[key]
      }
      pageData.sideTitle = '修改资料'
      pageData.showAdd = true
    }

    const sqblur = () => {
      console.log(111111111)
      dataForm.completionTime = dataForm.completionTime.toUpperCase()
    }

    //导出
    const exports = () => {
      if (selectedRowKeys.value.length === 0) {
        Message.error('请先勾选')
        return
      } else {
        //将表头拼接出来
        let head =
            '<th>编号</th><th>名称</th><th>备注</th><th>创建人</th><th>创建时间</th><th>最后修改人</th><th>最后修改时间</th>'
        //拿到当前表格数据与勾选的行做筛选

        let nowRow = table.dataList.filter(function (o) {
          return selectedRowKeys.value.indexOf(o['id']) !== -1
        })
        let body = ''
        nowRow.forEach(function (o) {
          body += '<tr><td>' + o['merceryCode'] + '</td>'
          body += '<td>' + o['merceryName'] + '</td>'
          body += '<td>' + o['remark'] + '</td>'
          body += '<td>' + o['createName'] + '</td>'
          body += '<td>' + o['createTime'] + '</td>'
          body += '<td>' + o['updateName'] + '</td>'
          body += '<td>' + o['updateTime'] + '</td>'
          body += '</tr>'
        })
        tableToXlsx(head, '布类资料', body)
        console.log(table)
      }
    }

    function tableToXlsx(head: any, filename: any, body: any) {
      const uri = 'data:application/vnd.ms-excel;base64,',
          template = `<html>
        <head><meta charset="UTF-8"></head>
        <body><table border="1"><tr>${head}</tr>${body}</table></body>
    </html>`

      const a = document.createElement('a')
      a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
      a.download = filename
      a.click()
      document.removeChild(a)
    }

    //模板下载
    const downloadHandler = () => {
      axios
          .get(baseURL + '/product/mercery/uploadMerceryModel', {
            responseType: 'blob',
            headers: {
              token: sessionStorage.getItem('USER-TOKEN-KEY'),
            },
          })
          .then((res) => {
            if (res.status === 200) {
              filedownload(res.data, '布类资料.xlsx')
            }
          })
    }
    //导入
    const importHandler = () => {
      const inputEle: HTMLInputElement = document.createElement('input')
      inputEle.type = 'file'
      inputEle.id = 'fileUploadExcel'
      inputEle.accept =
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
      inputEle.addEventListener('change', (e) => {
        const formData = new FormData()
        if (inputEle.files !== null) {
          formData.append('file', inputEle.files[0] || '')
        } else {
          Message.warning('未选择文件！')
          return
        }
        pageData.pageLoading = true
        axios
            .post(baseURL + '/product/mercery/analyseMerceryModel', formData, {
              headers: {
                'Content-Type': 'multipart/form-data',
                token: sessionStorage.getItem('USER-TOKEN-KEY'),
              },
            })
            .then((result) => {
              if (result.data['code'] === 200) {
                Message.success('导入成功')
              } else {
                Message.error(result.data.message)
              }
            })
            .finally(() => {
              pageData.pageLoading = false
              doRefresh()
            })
      })
      inputEle.click()
    }
    return {
      alone,
      alonell,
      scroll,
      scrollbar,
      tablediv,
      downloadHandler,
      importHandler,
      hasChiese,
      deleteHandler,
      sideOk,
      formRef,
      dataForm,
      addHandler,
      selectedRowKeys,
      pagination,
      // tableColumns,
      table,
      columns,
      tableCon,
      rowKey,
      pageData,
      queryData,
      editHandler,
      selectHandler,
      options,
      loading,
      handleSearch,
      exports,
      focusSel,
      paging,
      pagingChange,
      pagingSizeChange,
      // headerShow
      pages,
      sqblur,
      /**************** */
      rowData,
      defaultColDef,
      columnDefs,
      tc,
      gridReady,
      gridOption,
      /************************ */
      Search,
      CirclePlus,
      Delete,
    }
  },
  components: {Toolbar, },
}
</script>
<style scoped lang="less">
.pagings {
  margin-top: 10px;
  display: flex;
  justify-content: center;
}

.arco-input-wrapper {
  background-color: #fff !important;
  border: 1px solid #cccccc;
}

.arco-form-item-status-error .arco-input-wrapper:not(.arco-input-disabled),
.arco-form-item-status-error .arco-textarea-wrapper:not(.arco-textarea-disabled) {
  border: 1px solid #f53f3f;
}

.arco-select-view-single {
  background-color: #fff !important;
  border: 1px solid #cccccc;
}

.arco-select-view-single:hover {
  border: 1px solid #cccccc !important;
}

.arco-form-item-status-error .arco-select-view:not(.arco-select-view-disabled) {
  border: 1px solid #f53f3f;
}

/********************************************** */
.stbutencx {
  background-color: #409eff;

  &:hover {
    background-color: #79bbff;
  }
}

.ag-header-cell-resize::after {
  top: 0 !important;
  height: 100% !important;
}

.ag-cell {
  border-right: 1px solid #d9dddf !important;
}

.stbutenxz {
  background-color: #67c23a;

  &:hover {
    background-color: #b3e19d;
  }
}

:deep(.ag-cell-wrapper) {
  height: 100% !important;
}

:deep(.ag-cell-value) {
  height: 100% !important;
}

:deep(.arco-image-img ) {
  height: 100%;
}

:deep(.arco-tabs) {
  height: 100%;
}

:deep(.arco-tabs-content) {
  height: 100%;
}

:deep(.arco-tabs-content-list) {
  height: 100%;
}

/************************************************** */
</style>
